package users

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go"
	"strings"
	"time"
	"xpms/controllers"
)

// 登陆管理
type LoginController struct {
	controllers.BaseController
}

// @Title Login
// @Description Logs user into the system
// @Param	username		query 	string	true		"The username for login"
// @Param	password		query 	string	true		"The password for login"
// @Success 200 {string} login success
// @Failure 403 user not exist
// @router /login [get]
func (u *LoginController) Login() {
	username := u.GetString("username")
	password := u.GetString("password")
	if "" == username {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "请填写用户名"}
		u.ServeJSON()
	}
	if "" == password {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "请填写密码"}
		u.ServeJSON()
	}
	err, user := LoginUser(username, password)
	if err == nil {
		//u.SetSession("userLogin", fmt.Sprintf("%d", user.Id)+"||"+user.Username+"||"+user.Avatar)
		permission, _ := GetPermissionsAll(user.Id)
		//u.SetSession("userPermission", permission.Permission)
		//u.SetSession("userGroupid", permission.Groupid)
		usersProfile, _ := GetProfile(user.Id)
		exp := time.Now().Add(time.Hour * time.Duration(10000)).Unix()
		secret, _ := beego.AppConfig.String("secret")
		token, tokenErr := GenToken(user.Username, secret, user, usersProfile, strings.Split(permission.Groupid, ","), exp)
		if tokenErr != nil {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": "获取验证错误"}
			u.ServeJSON()
		}
		type data struct {
			Users        Users
			UsersProfile UsersProfile
			Token        string
			Exp          int64
		}
		d := &data{user, usersProfile, token, exp}
		u.Data["json"] = d
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": err}
	}
	u.ServeJSON()
}

// @Title logout
// @Description Logs out current logged in user session
// @Success 200 {string} logout success
// @router /logout [get]
func (u *LoginController) Logout() {
	u.DelSession("userLogin")
	u.DelSession("userPermission")
	u.DelSession("userGroupid")
	u.Data["json"] = map[string]interface{}{"code": 1, "message": "退出成功"}
	u.ServeJSON()
}

func GenToken(appID string, key string, user Users, profile UsersProfile, userRoleID []string, exp int64) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["exp"] = exp
	claims["iat"] = time.Now().Unix()
	claims["Issuer"] = appID
	userid := fmt.Sprintf("%d", user.Id)
	claims["userId"] = userid
	Departid := fmt.Sprintf("%d", profile.Departid)
	claims["Departid"] = Departid
	claims["account"] = user.Username
	claims["userName"] = profile.Realname
	claims["role"] = userRoleID
	token.Claims = claims
	tokenString, err := token.SignedString([]byte(key))
	return tokenString, err
}
